package com.winhxd.b2c.customer.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.winhxd.b2c.common.cache.Cache;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.constant.CacheName;
import com.winhxd.b2c.common.constant.CustomerConstant;
import com.winhxd.b2c.common.domain.PagedList;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.customer.condition.CustomerDistributorCondition;
import com.winhxd.b2c.common.domain.customer.condition.CustomerWalletCondition;
import com.winhxd.b2c.common.domain.customer.condition.DistributorQueryCondition;
import com.winhxd.b2c.common.domain.customer.enums.CustomerUserEnum;
import com.winhxd.b2c.common.domain.customer.enums.CustomerUserLevelEnum;
import com.winhxd.b2c.common.domain.customer.model.CustomerUserInfo;
import com.winhxd.b2c.common.domain.customer.vo.*;
import com.winhxd.b2c.common.domain.order.condition.OrderSummaryCondition;
import com.winhxd.b2c.common.domain.order.vo.OrderUserBaseSummaryVO;
import com.winhxd.b2c.common.domain.system.user.condition.CheckUserCondition;
import com.winhxd.b2c.common.domain.system.user.model.SysRole;
import com.winhxd.b2c.common.domain.system.user.model.SysUser;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.feign.customer.CustomerServiceClient;
import com.winhxd.b2c.common.feign.order.OrderDataStatisticsServiceClient;
import com.winhxd.b2c.common.feign.system.RoleServiceClient;
import com.winhxd.b2c.common.feign.system.UserServiceClient;
import com.winhxd.b2c.common.mq.MQDestination;
import com.winhxd.b2c.common.mq.StringMessageSender;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.customer.dao.CustomerUserInfoMapper;
import com.winhxd.b2c.customer.service.CustomerRevenueService;
import com.winhxd.b2c.customer.service.CustomerService;
import com.winhxd.b2c.customer.service.DistributorService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * @author：wangzekun
 * @Description:分销商业务处理
 * @date 2019.01.07 14:28
 */
@Service
public class DistributorServiceImpl implements DistributorService {

    @Autowired
    private CustomerUserInfoMapper customerUserInfoMapper;


    @Autowired
    private CustomerRevenueService customerRevenueService;

    @Autowired
    private CustomerService customerService;


    @Autowired
    private Cache cache;

    @Autowired
    private UserServiceClient userServiceClient;

    @Autowired
    private RoleServiceClient roleServiceClient;


    @Autowired
    private CustomerServiceClient customerServiceClient;


    @Autowired
    private OrderDataStatisticsServiceClient orderDataStatisticsServiceClient;

    @Autowired
    StringMessageSender stringMessageSender;

    private static final Logger logger = LoggerFactory.getLogger(DistributorServiceImpl.class);
    /**
     * @author 王泽坤
     * @Description: 后台新增一级分销商
     * @date 2019-01-07
     */
    @Override
    public Boolean saveFirstDistributer(CustomerDistributorCondition condition) {
        CustomerUserInfo customer = customerUserInfoMapper.selectCustomerUserInfoByPhone(condition.getCustomerMobile());
        SysUser sysUserFind=userServiceClient.getSysUserById(condition.getFirstParentId()).getData();
        logger.info("后台新增一级分销商开始:新增传的参数为："+ JsonUtil.toJSONString(condition));
        if(null==sysUserFind){
            logger.info("获取分销商所属的员工信息失败");
            throw new BusinessException(BusinessCode.CODE_200027);
        }
        //新增分销商信息 会员表不存在,员工表存在 那就提示不让添加
        if(null==customer){
            verfySysUserMobile(condition.getCustomerMobile(),null);
            customer = new CustomerUserInfo();
            enclosureCustomerUserInfo(condition,customer);
            //创建人 创建时间
            customer.setCreated(new Date());
            customer.setCreatedBy(condition.getUpdatedBy());
            customer.setCreatedByName(condition.getUpdatedByName());
            customer.setBindStatus(CustomerConstant.BIND_STATUS);
            //保存一级分销商到用户信息表lONG
            int saveFlag = customerUserInfoMapper.insertSelective(customer);
            //保持数据的一致性
            if(saveFlag >= 1)
            {
                //创建后台登录账号
               if(! saveSysUser(customer,sysUserFind))
               {
                   throw new BusinessException(BusinessCode.CODE_200034);
               }
            }else{
                throw new BusinessException(BusinessCode.CODE_200034);
            }
            logger.info("会员表或员工表都不存在此手机号" + condition.getCustomerMobile() + "添加此手机号为一级分销商成功！！！！");
        }else{
            logger.info("会员表存在此手机号" + condition.getCustomerMobile()+"升级分销商开始" );
            //升级分销商
            int level = customer.getLevel();
            if (CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode() == level) {
                logger.info("会员表中存在此手机号" + condition.getCustomerMobile() + "且此会员等级是一级分销商，因此不能添加");
                throw new BusinessException(BusinessCode.CODE_200030);
            }
            enclosureCustomerUserInfo(condition,customer);
            //修改人 修改时间
            customer.setUpdated(new Date());
            customer.setUpdatedBy(condition.getUpdatedBy());
            customer.setUpdatedByName(condition.getUpdatedByName());
            customer.setParentId(-1L);
            if(CustomerUserLevelEnum.CUSTOMER_LEVEL_0.getCode()==level){
                //创建后台登录账号
                if(saveSysUser(customer,sysUserFind)) {
                    //修改会员表
                    customerUserInfoMapper.updateByPrimaryKeySelective(customer);
                    // 换绑 操作  因为会员升级为一级经销商
                    stringMessageSender.send(MQDestination.UPDATE_CUSTOMER_PARENT_ID_MESSAGE, String.valueOf(customer.getId()));
                }else{
                    throw new BusinessException(BusinessCode.CODE_200034);
                }
                logger.info("手机号" + condition.getCustomerMobile()+"从会员升级为一级分销商成功！！！！" );
            }else{
                //二级分销商升级为一级分销商
                if(updateSysUser(customer,sysUserFind)){

                    //修改会员表
                    customerUserInfoMapper.updateByPrimaryKeySelective(customer);
                    //二级分销商升级为1级分销商后需要把二级分销商下面的会员的渠道也发生改变
                    CustomerDistributorCondition customerDistributorSecondCondition=new CustomerDistributorCondition();
                    customerDistributorSecondCondition.setId(customer.getId());
                    customerDistributorSecondCondition.setChannelId(condition.getChannelId());
                    //二级升1级后 需要把会员之前的绑定时间修改
                    //customerDistributorSecondCondition.setBindTime(new Date());
                    customerUserInfoMapper.updateUserLevelChannelByParentID(customerDistributorSecondCondition);
                }
                logger.info("手机号" + condition.getCustomerMobile()+"从二级分销商升级为一级分销商成功！！！！" );
            }
            //升级分销商需要把之前的会员二维码和二级分销商的二维码都重新置空
            customerUserInfoMapper.updateCodeUrl(customer.getId());
            //升级分销商都需要重新登录
            cache.del(CacheName.CUSTOMER_USER_INFO_TOKEN + customer.getToken());
        }

        return true;
    }



    /**
     * 修改分销商状态
     *
     * @param condition
     * @return
     */
    @Override
    public Boolean modifyDistributorStatus(CustomerDistributorCondition condition) {
        Long status=condition.getStatus()==1L?0:1L;
        condition.setStatus(status);
        int result = customerUserInfoMapper.updateUserStatusByID(condition);
        CustomerUserInfo customerUserInfo = customerUserInfoMapper.selectByPrimaryKey(condition.getId());
        if(CustomerUserEnum.CUSTOMER_STATUS_0.getCode()==condition.getStatus().intValue()){
            cache.del(CacheName.CUSTOMER_USER_INFO_TOKEN + customerUserInfo.getToken());
        }
        if(result>=1&&!Objects.equals(CustomerUserLevelEnum.CUSTOMER_LEVEL_0.getCode(), customerUserInfo.getLevel()) ){
            //调用员工表信息，更改员工表状态
            CheckUserCondition checkUserCondition=new CheckUserCondition();
            checkUserCondition.setCustomerId(condition.getId());
            SysUser sysuser=userServiceClient.getSysUserByCondition(checkUserCondition).getData();
            if(null==sysuser){
                throw new BusinessException(BusinessCode.CODE_200027);
            }
            if(0==status){
                userServiceClient.disabled(sysuser.getId());
            }else{
                userServiceClient.enable(sysuser.getId());
            }
        }
        boolean flag = result == 1 ? true : false;
        return flag;
    }

    /**
     * @author 王泽坤
     * @Description: 分销商列表查询
     * @date 2019-01-08
     */
    @Override
    public PagedList<CustomerDistributorVO> findDistributerListByCondition(CustomerDistributorCondition condition) {
        logger.info("分销商列表查询开始:查询传的参数为："+ JsonUtil.toJSONString(condition));
        List<Integer> levelList=new ArrayList<>();
        levelList=enclosureCustomerLevel(condition);
        condition.setLevelList(levelList);
        PagedList<CustomerDistributorVO> pagedList = new PagedList<>();
        // 校验分页参数
        if (condition.getPageSize() < CustomerConstant.DEFAULT_CURRENT_PAGE) {
            condition.setPageSize(CustomerConstant.DEFAULT_PAGE_SIZE);
        }
        if (condition.getPageNo() < CustomerConstant.DEFAULT_CURRENT_PAGE) {
            condition.setPageNo(CustomerConstant.DEFAULT_CURRENT_PAGE);
        }
        //查询分销商列表信息
        Page<Object> page = PageHelper.startPage(condition.getPageNo(), condition.getPageSize());
        List<CustomerDistributorVO> customers = customerUserInfoMapper.selectCustomerUserInfoListByCondition(condition);
        List<CustomerDistributorVO> customerDistributorList=new ArrayList<CustomerDistributorVO>();
        List<Long> idsList=new ArrayList<>();
        if(CollectionUtils.isNotEmpty(customers)) {
                for(CustomerDistributorVO customer : customers){
                    idsList.add(customer.getId());
            }
        }
        if(null==condition.getIsIntegral()||CollectionUtils.isNotEmpty(idsList)) {
            CustomerWalletCondition customerWalletCondition = new CustomerWalletCondition();
            customerWalletCondition.setIds(idsList);
            List<CustomerBaseCollectVO> customerBaseCollectVOList = customerService.findCustomerWallet(customerWalletCondition);
            if (CollectionUtils.isNotEmpty(customers)) {
                for (CustomerDistributorVO customer : customers) {
                    //查询积分和收益信息
                    if (CollectionUtils.isNotEmpty(customerBaseCollectVOList)) {
                        for (CustomerBaseCollectVO customerBaseCollectVO : customerBaseCollectVOList) {
                            if (null != customerBaseCollectVO && null != customer && customerBaseCollectVO.getCustomerId().equals(customer.getId())) {
                                //积分
                                customer.setIntegral(customerBaseCollectVO.getTotalIntegral());
                                //总收入
                                customer.setTotalIncome(customerBaseCollectVO.getTotalRevenue());
                            }
                        }
                    }
                    customerDistributorList.add(customer);
                }
            }
        }
        PageInfo<CustomerDistributorVO> pageInfo = new PageInfo(customerDistributorList);
        pagedList.setData(pageInfo.getList());
        pagedList.setPageNo(condition.getPageNo());
        pagedList.setPageSize(condition.getPageSize());
        pagedList.setTotalRows(page.getTotal());
        return pagedList;
    }

    /**
     * 据主键查询分销商换绑所需要的简单信息
     *
     * @param id
     * @return
     */
    @Override
    public CustomerDistributorSimpleVO findDistributerSimpleById(Long id) {
        logger.info("据主键查询分销商换绑所需要的简单信息:查询传的参数为："+ id);
        CustomerDistributorSimpleVO vo= customerUserInfoMapper.selectSimpleCustomerUserListById(id);
        //加入部门和所属员工id的回显
        CustomerUserInfo customer = customerUserInfoMapper.selectByPrimaryKey(id);
        SysUser user =null;
        //此处需要区分会员二级分销商和一级分销商
        if(null!=customer&&Objects.equals(CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode(), customer.getLevel()) ){
            //TODO 代码需要优化
            CheckUserCondition conditions = new CheckUserCondition();
            conditions.setCustomerId(id);
            user = userServiceClient.getSysUserByCondition(conditions).getData();
            if(null!=user){
                vo.setOrgId(user.getOrgId());
                vo.setOrgName(user.getOrgName());
                //所属员工和员工的姓名
                SysUser userParent=userServiceClient.getSysUserById(user.getParentId()).getData();
                vo.setUserId(userParent.getId());
                vo.setUserName(userParent.getUsername());
            }
        }else if(null!=customer&&!Objects.equals(CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode(), customer.getLevel())){
            //所属员工和员工的姓名
            CustomerUserInfo customerParent= customerUserInfoMapper.selectByPrimaryKey(customer.getParentId());
            vo.setUserId(customerParent.getId());
            vo.setUserName(customerParent.getNickName());
        }


        return vo;
    }

    /**
     * 一级分销商换绑
     *
     * @param condition
     * @return
     */
    @Override
    public Boolean modifyFirstDistributorBind(CustomerDistributorCondition condition) {
        logger.info("一级分销商换绑：传入的参数为"+ JsonUtil.toJSONString(condition));
        //1一级分销商的渠道信息发生改变
        //获取一级分销商信息
        //从json获取信息 channelName为channelId
        condition.setFirstParentId(condition.getUserId());
        //condition.setChannelId(Long.parseLong(condition.getChannelName()));
        CustomerUserInfo userInfo = customerUserInfoMapper.selectByPrimaryKey(condition.getId());
        userInfo.setChannelId(condition.getChannelId());
        userInfo.setUpdated(new Date());
        userInfo.setUpdatedBy(condition.getUpdatedBy());
        userInfo.setUpdatedByName(condition.getUpdatedByName());
        customerUserInfoMapper.updateByPrimaryKeySelective(userInfo);
        //一级分销商换绑
        //2一级分销商和员工的绑定关系，以及部门的绑定关系发生改变
        CheckUserCondition conditions = new CheckUserCondition();
        conditions.setCustomerId(userInfo.getId());
        SysUser user = userServiceClient.getSysUserByCondition(conditions).getData();
        //从json获取信息 userId为firstParentid
        user.setParentId(condition.getUserId());
        //修改orgId信息 跟上级保持一致
        SysUser userParent=userServiceClient.getSysUserById(user.getParentId()).getData();
        user.setOrgId(userParent.getOrgId());
        userServiceClient.modifySysUser(user);
        //3分销商换绑后需要把分销商下面的会员()的渠道都改变
        customerUserInfoMapper.updateUserLevelChannelByParentID(condition);
        //一級分銷商換綁后需要把一級分銷商下面的二级分销商的会员渠道也发生改变
        CustomerDistributorCondition distributorConditions=new CustomerDistributorCondition();
        distributorConditions.setFirstParentId(condition.getId());
        distributorConditions.setLevel(CustomerUserLevelEnum.CUSTOMER_LEVEL_2.getCode());
        List<Integer> levelList=enclosureCustomerLevel(distributorConditions);
        distributorConditions.setLevelList(levelList);
        List<CustomerDistributorVO> distributorVoList=customerUserInfoMapper.selectCustomerUserInfoListByCondition(distributorConditions);
        List<Long> userSecondList=new ArrayList<Long>();
        distributorVoList.forEach((vo) -> userSecondList.add(vo.getId()));
        if(CollectionUtils.isNotEmpty(userSecondList)){
            for (Long id:userSecondList
                 ) {
                CustomerDistributorCondition customerDistributorSecondCondition=new CustomerDistributorCondition();
                customerDistributorSecondCondition.setChannelId(condition.getChannelId());
                customerDistributorSecondCondition.setId(id);
                customerUserInfoMapper.updateUserLevelChannelByParentID(customerDistributorSecondCondition);
            }
        }
        return true;
    }

    /**
     * 二级分销商换绑
     *
     * @param condition
     * @return
     */
    @Override
    public Boolean modifySecondDistributorBind(CustomerDistributorCondition condition) {
        logger.info("二级分销商换绑：传入的参数为"+ JsonUtil.toJSONString(condition));
        //二级分销商换绑
       //获取绑定的一级分销商的id 并根据id获取相关信息 此处的USERID是会员表的主键id
        CustomerUserInfo userInfoParent = customerUserInfoMapper.selectByPrimaryKey(condition.getUserId());
        //获取员工表的id
        CheckUserCondition conditions = new CheckUserCondition();
        conditions.setCustomerId(condition.getUserId());
        SysUser userParent = userServiceClient.getSysUserByCondition(conditions).getData();
        //获取当前二级分销商在用户表的id 并根据id获取相关信息
        CustomerUserInfo userInfo = customerUserInfoMapper.selectByPrimaryKey(condition.getId());
        userInfo.setChannelId(userInfoParent.getChannelId());
        userInfo.setParentId(condition.getUserId());
        userInfo.setUpdated(new Date());
        userInfo.setUpdatedBy(condition.getUpdatedBy());
        userInfo.setUpdatedByName(condition.getUpdatedByName());
        customerUserInfoMapper.updateByPrimaryKeySelective(userInfo);
        //二级分销商换绑后需要把二级分销商下面的会员的渠道发生改变
        condition.setChannelId(userInfoParent.getChannelId());
        customerUserInfoMapper.updateUserLevelChannelByParentID(condition);
        //更改员工表中二级分销商的上级信息
        conditions.setCustomerId(condition.getId());
        SysUser userSon=userServiceClient.getSysUserByCondition(conditions).getData();
        userSon.setParentId(userParent.getId());
        userServiceClient.modifySysUser(userSon);
        return true;
    }

    /**
     * @author 王泽坤
     * @Description:
     * 根据主键id查询分销商详情
     * @date 2019-01-08
     */
    @Override
    public CustomerDetailVO findDistributerDeatilById(Long id) {
        logger.info("根据主键id查询分销商详情信息：传入的参数为"+ id);
        CustomerDetailVO vo= customerUserInfoMapper.selectDetailCustomerUserListById(id);
        //获取一级分销商和二级分销商的会员数量
        vo.setMemberCount(customerUserInfoMapper.countMemberCountByParentId(id));
        //查询会员和二级分销商的上级信息
        if(Objects.equals(CustomerUserLevelEnum.CUSTOMER_LEVEL_0.getCode(), vo.getLevel())||
                Objects.equals(CustomerUserLevelEnum.CUSTOMER_LEVEL_2.getCode(), vo.getLevel())){
            CustomerUserInfo userInfoParent=customerUserInfoMapper.selectByPrimaryKey(vo.getParentId());
            if(null!=userInfoParent){
                vo.setParentId(userInfoParent.getId());
                //会员的上级分销等级
                //vo.setLevel(userInfoParent.getLevel());
                vo.setParentWechatName(userInfoParent.getWechatName());
            }
        }else if( Objects.equals(CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode(), vo.getLevel()) ){
            //查询一级分销商下面的二级分销商的数量信息
            CheckUserCondition conditions = new CheckUserCondition();
            conditions.setCustomerId(vo.getId());
            SysUser user = userServiceClient.getSysUserByCondition(conditions).getData();
           if (null == user) {
                    throw new BusinessException(BusinessCode.CODE_200032);
                }
           vo.setDistributorSecondCount(customerUserInfoMapper.countDistributorSecondByParentId(vo.getId()));
           //如果是一级分销商不显示parentId
           vo.setParentId(null);
        }
        List<Long> idsList=new ArrayList<Long>();
        idsList.add(id);
        CustomerWalletCondition condition=new CustomerWalletCondition();
        condition.setIds(idsList);
        List<CustomerBaseCollectVO> customerBaseCollectVOList=customerService.findCustomerWallet(condition);
        if(CollectionUtils.isEmpty(customerBaseCollectVOList)){
            return vo;
        }
        CustomerBaseCollectVO customerBaseCollectVO = customerBaseCollectVOList.get(0);
        if(null!=customerBaseCollectVO){
            //余额:可提现余额
            vo.setBalance(customerBaseCollectVO.getBalance());
            //累计提现收入
            vo.setCumulatedBalance(customerBaseCollectVO.getWithdraw());
            //积分
            vo.setIntegral(customerBaseCollectVO.getTotalIntegral());
            //总收入
            vo.setTotalIncome(customerBaseCollectVO.getTotalRevenue());
        }
        //订单相关vo
        OrderSummaryCondition orderSummaryCondition=new OrderSummaryCondition();
        orderSummaryCondition.setCustomerId(id);
        orderSummaryCondition.setUserLevel(vo.getLevel());
        OrderUserBaseSummaryVO orderUserBaseSummaryVO=orderDataStatisticsServiceClient.getUserBaseSummarySummary(orderSummaryCondition).getData();
        if(null!=orderUserBaseSummaryVO){
            //他的订单
            vo.setOrder(orderUserBaseSummaryVO.getOrderNum());
            //待转正收入
            vo.setPositiveBalance(orderUserBaseSummaryVO.getTotal());
        }
        return vo;
    }


    /**
     * 后台保存分销商详情信息
     *
     * @param condition
     * @return
     */
    @Override
    public Boolean modifyDistributor(CustomerDistributorCondition condition) {
        logger.info("后台保存分销商详情信息：传入的参数为"+ JsonUtil.toJSONString(condition));
        CustomerUserInfo customerUserInfo= customerUserInfoMapper.selectByPrimaryKey(condition.getCustomerId());
        CustomerUserInfo info=new CustomerUserInfo();
        info.setId(condition.getCustomerId());
        info.setNickName(condition.getNickName());
        info.setCustomerMobile(condition.getCustomerMobile());
        info.setUpdated(new Date());
        info.setUpdatedBy(condition.getUpdatedBy());
        info.setUpdatedByName(condition.getUpdatedByName());
        if(null!=condition.getSex()&&!"".equals(condition.getSex())){
            info.setSex(Integer.parseInt(condition.getSex()));
        }
        info.setBirthday(condition.getBirthday());
        //分销商修改了手机号需要同时去修改员工表的信息
        CustomerUserInfo userInfo=customerUserInfoMapper.selectByPrimaryKey(condition.getCustomerId());
        if(CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode()==userInfo.getLevel()&&CustomerUserLevelEnum.CUSTOMER_LEVEL_2.getCode()==userInfo.getLevel()) {
            CheckUserCondition checkUserCondition = new CheckUserCondition();
            checkUserCondition.setCustomerId(userInfo.getId());
            SysUser sysUser = userServiceClient.getSysUserByCondition(checkUserCondition).getData();
            sysUser.setAccount(condition.getCustomerMobile());
            sysUser.setMobile(condition.getCustomerMobile());
            if(BusinessCode.CODE_OK!=userServiceClient.modifySysUser(sysUser).getCode()){
                throw new BusinessException(BusinessCode.CODE_200034);
            }else{
                customerUserInfoMapper.updateByPrimaryKeySelective(info);
            }

        }else{
            customerUserInfoMapper.updateByPrimaryKeySelective(info);
        }
        //保存会员和分销商详情信息后  如果手机号发生了改变需要重新登录
        if(null!=customerUserInfo&&null!=customerUserInfo.getCustomerMobile()&&null!=condition.getCustomerMobile()&&!customerUserInfo.getCustomerMobile().equals(condition.getCustomerMobile())){
            logger.info("修改了手机号修改前手机号:"+customerUserInfo.getCustomerMobile()+"修改后手机号："+condition.getCustomerMobile()+"需要重新登录!!!!!");
            cache.del(CacheName.CUSTOMER_USER_INFO_TOKEN + customerUserInfo.getToken());
        }
        return true;
    }

    /**
     * @param condition
     * @return  CustomerStoreVO
     * @author wangzekun
     * @date 2019/1/15
     * @Description 根据渠道ID和等级查询分销商信息
     */
    @Override
    public List<CustomerUserInfoVO> findDistributorListByChannelIdAndLevel(CustomerDistributorCondition condition) {
        return customerUserInfoMapper.selectDistributorListByChannelIdAndLevel(condition);
    }



    /**
     * 保存一级分销商信息进行组装
     * @param condition
     * @param userInfo
     * @return 2019-1-14
     */
    private CustomerUserInfo  enclosureCustomerUserInfo(CustomerDistributorCondition condition,CustomerUserInfo userInfo){
        //手机号
        userInfo.setCustomerMobile(condition.getCustomerMobile());
        //昵称
        userInfo.setNickName(condition.getNickName());
        //性别 女0 男1 不填数据库存null
        if (StringUtils.isEmpty(condition.getSex())) {
            userInfo.setSex(null);
        } else {
            Integer sex = "女".equals(condition.getSex()) ? 0 : 1;
            userInfo.setSex(sex);
        }
        //一级分销商默认状态激活 1激活,0冻结
        userInfo.setStatus(CustomerUserEnum.CUSTOMER_STATUS_1.getCode());
        //渠道id
        userInfo.setChannelId(condition.getChannelId());
        //会员等级1:一级分销商 2：二级分销商 0：会员
        userInfo.setLevel(CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode());
        userInfo.setStoreName(userInfo.getStoreName()==null?condition.getNickName()+"的小店":userInfo.getStoreName());
        Short status=1;
        userInfo.setStoreStatus(status);
        return userInfo;
    }



    /**
     * 会员换绑
     *
     * @param condition
     * @return
     */
    @Override
    public Boolean modifyMemberDistributorBind(CustomerDistributorCondition condition) {
        logger.info("会员换绑：传入的参数为"+ JsonUtil.toJSONString(condition));
        //会员换绑
        // 此处的ID是会员主键id 此处的USERID是绑定的分销商的parentid主键id
        CustomerUserInfo userInfoParent = customerUserInfoMapper.selectByPrimaryKey(condition.getUserId());
        CustomerUserInfo userInfo = customerUserInfoMapper.selectByPrimaryKey(condition.getId());
        userInfo.setChannelId(userInfoParent.getChannelId());
        userInfo.setParentId(condition.getUserId());
        userInfo.setBindTime(new Date());
        //会员换绑时候需要清除掉之前的访问时间
        userInfo.setAccessTime(null);
        userInfo.setUpdated(new Date());
        userInfo.setUpdatedBy(condition.getUpdatedBy());
        userInfo.setUpdatedByName(condition.getUpdatedByName());
        customerUserInfoMapper.updateMemberDistributorBind(userInfo);
        return true;
    }


    /**
     *
     * @param condition
     * @param condition
     * @return
     */
    private List<Integer>   enclosureCustomerLevel(CustomerDistributorCondition condition){
        List<Integer> levelList=new ArrayList<>();
        if(null==condition||null==condition.getFlag()){
            if(null!=condition.getLevel()){
                levelList.add(condition.getLevel());
            }
            return levelList;
        }
        //flag 判断查询标识 1:代表查询分销商(包括一级分销商和二级分销商) 2代表查询会员
        if(1==condition.getFlag()){
            if(null!=condition.getLevel()){
                levelList.add(condition.getLevel());
            }else{
                levelList.add(CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode());
                levelList.add(CustomerUserLevelEnum.CUSTOMER_LEVEL_2.getCode());
                levelList.add(CustomerUserLevelEnum.CUSTOMER_LEVEL_3.getCode());
            }

        }else if(2==condition.getFlag()){
            levelList.add(CustomerUserLevelEnum.CUSTOMER_LEVEL_0.getCode());
        }
        return levelList;
    }

    /**
     * 创建后台登录账号
     * @param customerUserInfo
     * @param sysUserFind
     */
    private Boolean saveSysUser(CustomerUserInfo customerUserInfo,SysUser sysUserFind){
        //获取一级分销商的默认角色id TODO
        ResponseResult<SysRole> roleResult = roleServiceClient.getDefaultRole();
        if(roleResult.getCode()!=0){
            throw new BusinessException(BusinessCode.CODE_1001);
        }
        SysRole sysRole=roleResult.getData();
        SysUser sysUser = new SysUser();
        sysUser.setOrgId(sysUserFind.getOrgId());
        sysUser.setRoleId(sysRole.getId());
        sysUser.setCustomerId(customerUserInfo.getId());
        sysUser.setParentId(sysUserFind.getId());
        //保存一级分销商到员工表
        return customerService.saveSystemUser(customerUserInfo,sysUser,customerUserInfo.getUpdatedBy(),customerUserInfo.getUpdatedByName());
    }

    /**
     * 修改后台登录账号
     * @param customer
     * @param sysUserFind
     */
    private boolean updateSysUser(CustomerUserInfo customer,SysUser sysUserFind){
        CheckUserCondition conditions = new CheckUserCondition();
        conditions.setCustomerId(customer.getId());
        ResponseResult<SysUser> userResult = userServiceClient.getSysUserByCondition(conditions);
        if(userResult.getCode()!=0){
            throw new BusinessException(BusinessCode.CODE_1001);
        }
        SysUser sysUser = userResult.getData();
        if(null==sysUser){
            return false;
        }
        sysUser.setLevel(CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode());
        sysUser.setParentId(sysUserFind.getId());
        sysUser.setOrgId(sysUserFind.getOrgId());
        sysUser.setUpdatedBy(customer.getUpdatedBy());
        sysUser.setUpdatedByName(customer.getUpdatedByName());
        //修改员工表（涉及到员工角色问题）
        return userServiceClient.modifySysUser(sysUser).getCode()==0?true:false;
    }

    /**
     * 查询分销商下面的会员
     * @param condition
     * @return
     */
    @Override
    public List<CustomerUserInfoVO> findDistributorMemberList(DistributorQueryCondition condition) {
        if (null == condition || null==condition.getCustomerId()) {
            throw new BusinessException(BusinessCode.CODE_200035);
        }
        return customerUserInfoMapper.selectDistributorMemberList(condition);
    }


    /**
     * 校验手机号是否在员工表的账号和手机号字段中
     * @param mobile
     */

    @Override
    public void  verfySysUserMobile(String mobile,Long id){
        CheckUserCondition checkUserCondition=new CheckUserCondition();
        checkUserCondition.setAccount(mobile);
        checkUserCondition.setCustomerId(id);
        List<SysUser> sysUserFindByAccount=userServiceClient.findUserListByCondition(checkUserCondition).getData();
        if(CollectionUtils.isNotEmpty(sysUserFindByAccount)){
            logger.info("在员工表存在此手机号信息,不能添加一级分销商----手机号：{}",mobile);
            throw new BusinessException(BusinessCode.CODE_200034);
        }
    }

}
